﻿namespace Sgr.BackGroundTasks
{
    /// <summary>
    /// 后台任务统一调用适配器：屏蔽具体泛型数据类型，便于非泛型执行器统一处理。
    /// </summary>
    public interface IBackGroundTaskInvoker
    {
        Task InvokeAsync(object? data, CancellationToken cancellationToken = default);
    }

    /// <summary>
    /// 有入参任务的强类型适配器。
    /// </summary>
    public sealed class BackGroundTaskInvoker<TTask, TData> : IBackGroundTaskInvoker
        where TTask : class, IBackGroundTask<TData>
        where TData : class
    {
        private readonly TTask _task;

        public BackGroundTaskInvoker(TTask task) => _task = task ?? throw new ArgumentNullException(nameof(task));

        public Task InvokeAsync(object? data, CancellationToken cancellationToken = default)
        {
            if (data is not TData typed)
                throw new BackGroundTaskException($"任务数据类型不匹配，期望 {typeof(TData).FullName}，实际 {data?.GetType().FullName ?? "null"}");
            return _task.ExecuteAsync(typed, cancellationToken);
        }
    }

    /// <summary>
    /// 无入参任务的适配器
    /// </summary>
    public sealed class BackGroundTaskNoArgInvoker<TTask> : IBackGroundTaskInvoker
        where TTask : class, IBackGroundTask
    {
        private readonly TTask _task;

        public BackGroundTaskNoArgInvoker(TTask task) => _task = task ?? throw new ArgumentNullException(nameof(task));

        public Task InvokeAsync(object? data, CancellationToken cancellationToken = default)
        {
            // data 直接忽略
            return _task.ExecuteAsync(cancellationToken);
        }
    }
}